package com.chang.coupon.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.common.utils.PageUtils;
import com.chang.common.utils.Query;
import com.chang.coupon.entity.SeckillSessionEntity;
import com.chang.coupon.entity.SeckillSkuRelationEntity;
import com.chang.coupon.mapper.SeckillSessionDao;
import com.chang.coupon.service.SeckillSessionService;
import com.chang.coupon.service.SeckillSkuRelationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Resource
    SeckillSkuRelationService seckillSkuRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatest3DaySession() {
        // 获取当前时间并计算最近三天
        Date date = DateUtil.date();
        Date beginDate = DateUtil.beginOfDay(date);
        Date endDate = DateUtil.offsetDay(beginDate, 3);

        List<SeckillSessionEntity> list = list(new LambdaQueryWrapper<SeckillSessionEntity>().between(SeckillSessionEntity::getStartTime, beginDate, endDate));
        log.info("获取三天内的秒杀场次信息list:{}", list);
        if (list != null && list.size() > 0) {
            // 将秒杀商品信息封装
            List<SeckillSessionEntity> finalList = list.stream().map(item -> {
                Long id = item.getId();
                // 从关联表查询关联的秒杀信息
                List<SeckillSkuRelationEntity> skuRelationEntities = seckillSkuRelationService.list(new LambdaQueryWrapper<SeckillSkuRelationEntity>().eq(SeckillSkuRelationEntity::getPromotionSessionId, id));
                log.info("根据场次信息查询场次对应活动商品集合skuRelationEntities:{}", skuRelationEntities);
                item.setRelationSkus(skuRelationEntities);
                return item;
            }).toList();
            return finalList;
        }
        return null;
    }
}